﻿
/// <reference path="../../Common/socialshop-utils.js" />


Pages_ListAdmin = new function () {
    this.textPassNotChange = "[Không đổi]";
    this.adminID = -1;
    this.userName = "";
    this.status = -1;
    this.roleID = -1;
    this.fromDate = "";
    this.toDate = "";
    this.typeButton = 0;
    //0:Thêm mới, 1: Cập nhật

    this.m_objPageListAdmin = new VtcPaging("divListAdminPaging", "Pages_ListAdmin.bindData", "pagingCss", 10, CONSTANT.PAGE_DISPLAY);

    this.documentReady = function () {

        $("#txtUserName").val('');
        $("#txtUserName").focus();
        $("#txtAdminID").val('');

        var _date = new Date();
        //bind dữ liệu cho ToDate
        $("#txtToDate").val(Pages_ListAdmin.convertDate(_date));

        //bind dữ liệu cho FromDate
        _date.setDate(_date.getDate() - 365);
        $("#txtFromDate").val(Pages_ListAdmin.convertDate(_date));

        Pages_ListAdmin.bindStatus();
        Pages_ListAdmin.bindRole();

        this.bindData(1, this.m_objPageListAdmin.pageSize);
    };

    this.bindData = function (_cur, _ps) {
        Loading.showProcess();
        Pages_ListAdmin.toDate = $("#txtToDate").val();
        Pages_ListAdmin.fromDate = $("#txtFromDate").val();
        Pages_ListAdmin.adminID = $("#txtAdminID").val();
        if (Pages_ListAdmin.adminID == "")
            Pages_ListAdmin.adminID = -1;

        $.ajax({
            type: "GET",
            url: "/handler/HandlerConfig.ashx",
            data: { userName: Pages_ListAdmin.userName, adminID: Pages_ListAdmin.adminID, status: Pages_ListAdmin.status, roleID: Pages_ListAdmin.roleID, fromDate: Pages_ListAdmin.fromDate, toDate: Pages_ListAdmin.toDate, currentPage: _cur, pageSize: _ps, t: "GetListAdmin" },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (data) {
                Pages_ListAdmin.processData(data, _cur);
                Loading.closeProcess();
            }
        });

    };

    this.processData = function (data, _cur) {
        $("#spTotalAdmin").html('(' + data.TotalRecord.toString() + ')');
        $("#divListAdmin").setTemplateURL("/Template/Pages/Config/ListAdmin.htm");
        $("#divListAdmin").processTemplate(data);
        Pages_ListAdmin.setStyleRow("#divListAdmin");
        Pages_ListAdmin.m_objPageListAdmin.bindPaging(_cur, data.TotalRecord);
        if (data.TotalRecord <= Pages_ListAdmin.m_objPageListAdmin.pageSize) {
            $("#divListAdminPaging").attr('style', 'display:none');
        }
        else {
            $("#divListAdminPaging").attr('style', 'display:block');
        }
    };

    this.bindStatus = function () {
        $("#ddlStatusAdmin").append('<option value="-1">[--' + MESSAGE.all + '--]</option>');
        for (var i = 1; i < 3; i++) {
            $("#ddlStatusAdmin").append('<option value="' + i + '">' + Pages_ListAdmin.convertStatus(i) + '</option>')
        }
    };

    this.bindRole = function () {
        $("#ddlRoleAdmin").append('<option value="-1">[--' + MESSAGE.all + '--]</option>');
        $.ajax({
            type: "GET",
            url: "/Handler/HandlerConfig.ashx",
            data: { t: 'GetListRole' },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (data) {
                for (var i = 0; i < data.Items.length; i++) {
                    $("#ddlRoleAdmin").append('<option value="' + data.Items[i].RoleID + '">' + data.Items[i].Name + '</option>')
                }
            }
        });
    };

    this.searchListAdmin = function () {
        if (!this.validateSearch()) return;
        Pages_ListAdmin.userName = $("#txtUserName").val();
        Pages_ListAdmin.status = $("#ddlStatusAdmin").val();
        Pages_ListAdmin.roleID = $("#ddlRoleAdmin").val();
        Pages_ListAdmin.bindData(1, Pages_ListAdmin.m_objPageListAdmin.pageSize);
    };

    // Kiem tra du lieu truoc khi tim kiem
    this.validateSearch = function () {
        if (!IsNumeric($("#txtAdminID").val())) {
            jAlert(MESSAGE.errorAdminIDNotIsNumberic, MESSAGE.title, function () {
                $("#txtAdminID").focus();
            });
            return false;
        }

        if ($("#txtFromDate").val() == '') {
            jAlert(MESSAGE.datetimenull, MESSAGE.title, function () {
                $("#txtFromDate").focus();
            });
            return false;
        }
        if ($("#txtToDate").val() == '') {
            jAlert(MESSAGE.datetimenull, MESSAGE.title, function () {
                $("#txtToDate").focus();
            });
            return false;
        }

        if (Untils.isDate($("#txtFromDate").val()) < 0) {
            jAlert(MESSAGE.errorFormatDate, MESSAGE.title, function () {
                $("#txtFromDate").focus();
            });
            return false;
        }

        if (Untils.isDate($("#txtToDate").val()) < 0) {
            jAlert(MESSAGE.errorFormatDate, MESSAGE.title, function () {
                $("#txtToDate").focus();
            });
            return false;
        }
        if (!Untils.DateCompare($("#txtFromDate").val(), $("#txtToDate").val())) {
            jAlert(MESSAGE.erroDateTime, MESSAGE.title, function () {
                $("#txtToDate").focus();
            });
            return false;
        }
        return true;
    };


    $("#btnSearch").live('click', function () {
        Pages_ListAdmin.searchListAdmin();
    });

    $("#aEditAdmin").live('click', function () {
        Pages_ListAdmin.displayControl(false);
        $("#divRoleAdmin").show();
        Pages_ListAdmin.adminID = $(this.parentNode).attr("id").substring(4);
        Pages_ListAdmin.typeButton = 1;
        $.ajax({
            type: "GET",
            url: "/handler/HandlerConfig.ashx",
            data: { adminID: Pages_ListAdmin.adminID, t: "GetAdminInfo" },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (data) {
                $("#txtUserNameUpdate").attr('disabled', 'disabled');
                $("#txtUserNameUpdate").val(data.UserName);
                $("#txtPassUpdate").val(Pages_ListAdmin.textPassNotChange);

                $("#txtFullNameUpdate").attr('disabled', 'disabled');
                $("#txtFullNameUpdate").val(data.FullName);

                $("#txtBirthdayUpdate").attr('disabled', 'disabled');
                if (data.Birthday != null) {
                    $("#txtBirthdayUpdate").val(COMMON.jSonDateToString(data.Birthday, 1));
                }
                else {
                    $("#txtBirthdayUpdate").val('');
                }

                $("#txtYMUpdate").attr('disabled', 'disabled');
                if (data.YM != null) {
                    $("#txtYMUpdate").val(data.YM);
                }
                else {
                    $("#txtYMUpdate").val('');
                }

                $("#txtTelephoneUpdate").attr('disabled', 'disabled');
                if (data.Phone != null) {
                    $("#txtTelephoneUpdate").val(data.Phone);
                }
                else {
                    $("#txtTelephoneUpdate").val('');
                }

                if (data.Description != null) {
                    var _des = data.Description.replace(/<br\/>/g, '\n');
                    _des = Encoder.htmlDecode(_des);
                    $("#txtDescriptionUpdate").val(_des);
                }
                else {
                    $("#txtDescriptionUpdate").val('');
                }

                $("#divCreateDate").attr('style', 'display:block');
                $("#lbCreateDateUpdate").text(COMMON.jSonDateToString(data.CreateDate, 1));

                //bind du lieu cho ddlStatusUpdate
                $(".optStatus").remove();
                var _status = data.Status;
                for (var i = 1; i < 3; i++) {
                    if (i == _status) {
                        $("#ddlStatusUpdate").append('<option class="optStatus" value="' + i + '" selected="selected">' + Pages_ListAdmin.convertStatus(i).toString() + '</option>');
                    }
                    else {
                        $("#ddlStatusUpdate").append('<option class="optStatus" value="' + i + '">' + Pages_ListAdmin.convertStatus(i).toString() + '</option>');
                    }
                }

                //bind list Role
                Pages_ListAdmin.bindRoleInAdmin();
            }
        });

    });

    this.bindRoleInAdmin = function () {
        $.ajax({
            type: "GET",
            url: "/Handler/HandlerConfig.ashx",
            data: { adminID: Pages_ListAdmin.adminID, t: 'GetListRoleInAdmin' },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (data) {
                $("#divListRoleAdmin").setTemplateURL("/Template/Pages/Config/ListRoleInAdmin.htm");
                $("#divListRoleAdmin").processTemplate(data);
                var m_stt = 0;
                $('#divSTT', '#divListRoleAdmin').each(function () {
                    m_stt++;
                    $(this).text(m_stt);
                });
                Pages_ListAdmin.setStyleRow("#divListRoleAdmin");
                $("#divRoleAdmin").slideDown(0);
            }
        });
    };


    $("#btnAddAdmin").live('click', function () {
        Pages_ListAdmin.displayControl(false);
        $("#divRoleAdmin").hide();
        Pages_ListAdmin.typeButton = 0;
        $("#txtPassUpdate").val('');

        $("#txtUserNameUpdate").attr('disabled', '');
        $("#txtUserNameUpdate").val("");

        $("#txtFullNameUpdate").attr('disabled', '');
        $("#txtFullNameUpdate").val("");

        $("#txtBirthdayUpdate").attr('disabled', '');
        $("#txtBirthdayUpdate").val("");

        $("#txtYMUpdate").attr('disabled', '');
        $("#txtYMUpdate").val("");

        $("#txtTelephoneUpdate").attr('disabled', '');
        $("#txtTelephoneUpdate").val("");

        $("#txtDescriptionUpdate").val("");

        $("#divCreateDate").attr('style', 'display:none');

        //bind du lieu cho ddlStatusUpdate
        $(".optStatus").remove();
        for (var i = 2; i > 0; i--) {
            $("#ddlStatusUpdate").append('<option class="optStatus" value="' + i + '" selected="selected">' + Pages_ListAdmin.convertStatus(i).toString() + '</option>');
        }
    });

    $("#aDeleteAdmin").live('click', function () {

        Pages_ListAdmin.adminID = $(this.parentNode).attr("id").substring(6);
        jConfirm(MESSAGE.confirmDeleteAdmin, MESSAGE.confirm, function (result) {
            if (result) {
                Loading.showProcess();
                var _data = {
                    adminID: Pages_ListAdmin.adminID
                };
                $.ajax({
                    type: "POST",
                    url: "/WebService/WSConfig.asmx/DeleteAdmin",
                    data: JSON.encode(_data),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    cache: false,
                    success: function (data) {
                        if (true) {
                            jAlert(MESSAGE.deleteSuccess, MESSAGE.title);
                            Pages_ListAdmin.bindData(1, Pages_ListAdmin.m_objPageListAdmin.pageSize);
                        }
                        Loading.closeProcess();
                    }
                });
            }
        });
    });


    $("#btnUpdateAdmin").live('click', function () {
        Loading.showProcess();
        var _data = "";
        if (Pages_ListAdmin.typeButton == 0) { //thêm mới
            if (($("#txtUserNameUpdate").val() == "") || ($("#txtFullNameUpdate").val() == "") || ($("#txtPassUpdate").val() == "")) {
                Loading.closeProcess();
                jAlert(MESSAGE.errorInfo, MESSAGE.title);
                return;
            }

            _data =
                {
                    userName: $("#txtUserNameUpdate").val(),
                    pass: $("#txtPassUpdate").val(),
                    fullName: $("#txtFullNameUpdate").val(),
                    birthday: $("#txtBirthdayUpdate").val(),
                    YM: $("#txtYMUpdate").val(),
                    phone: $("#txtTelephoneUpdate").val(),
                    description: $("#txtDescriptionUpdate").val(),
                    status: $("#ddlStatusUpdate").val()
                };

            $.ajax({
                type: "POST",
                url: "/WebService/WSConfig.asmx/AddAdmin",
                data: JSON.encode(_data),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                cache: false,
                success: function (data) {
                    if (data.d > 0) {
                        jAlert(MESSAGE.addSuccess, MESSAGE.title);
                        Pages_ListAdmin.bindData(1, Pages_ListAdmin.m_objPageListAdmin.pageSize);
                        Pages_ListAdmin.displayControl(true);
                    }
                    else {
                        if (data.d == -2) {
                            jAlert("Admin với tài khoản này đã tồn tại!", MESSAGE.title);
                        }
                        else
                            if (data.d == -1) {
                                jAlert(MESSAGE.notPermission, MESSSAGE.title);
                            }
                            else {
                                jAlert(MESSAGE.error, MESSAGE.title);
                            }
                    }
                }
            });
        };

        if (Pages_ListAdmin.typeButton == 1) {
            _data =
                {
                    adminID: Pages_ListAdmin.adminID,
                    description: $("#txtDescriptionUpdate").val(),
                    status: $("#ddlStatusUpdate").val()
                };

            $.ajax({
                type: "POST",
                url: "/WebService/WSConfig.asmx/UpdateAdminStatus",
                data: JSON.encode(_data),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                cache: false,
                success: function (data) {
                    if (data.d > 0) {
                        jAlert(MESSAGE.updateSuccess, MESSAGE.title);
                        Pages_ListAdmin.bindData(1, Pages_ListAdmin.m_objPageListAdmin.pageSize);
                        Pages_ListAdmin.displayControl(true);
                    }
                    else {
                        jAlert(MESSAGE.error, MESSAGE.title);
                    }
                }
            });
        }
        Loading.closeProcess();
    });

    $("#btnCancelAdmin").live('click', function () {
        Pages_ListAdmin.displayControl(true);
    });

    //Xủa ly khi nhấn nút thêm mới Role cho Admin
    $("#btnAddRoleToAdmin").live('click', function () {
        ShowListRole.showPopup(Pages_ListAdmin.adminID);

    });

    //Xu lý khi nhấn xóa một role khỏi các quyền cuae Admin
    $("#aDeleteRoleFromAdmin").live('click', function () {
        Loading.showProcess();
        var _perID = $(this.parentNode).attr("id").substring(6);
        var _data = {
            permisionID: _perID
        }
        $.ajax({
            type: "POST",
            url: "/WebService/WSConfig.asmx/DeletePermission",
            data: JSON.encode(_data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (data) {
                Pages_ListAdmin.bindRoleInAdmin();
                jAlert(MESSAGE.deleteSuccess, MESSAGE.title);
                Loading.closeProcess();
            }
        });

    });


    // Ẩn hiện các khối Tìm kiếm, danh sách và thông tin
    this.displayControl = function (m_bool) {
        if (m_bool) {
            $("#divAdminDetail").slideUp(0, function () {
                $("#divSearch").slideDown(0, function () {
                    $("#divList").slideDown(0);
                });

            });
        }
        else {
            $("#divList").slideUp(0, function () {
                $("#divSearch").slideUp(0, function () {
                    $("#divAdminDetail").slideDown(0);
                });
            });
        }
    };

    this.setStyleRow = function (m_selParent) {
        var m_stt = 0;
        $('#divItem', m_selParent).each(function () {
            m_stt++;
            if ((m_stt % 2) == 0) {
                $(this.parentNode).addClass('even');
            }
            else {
                $(this.parentNode).addClass('odd');
            }
        });
    };

    this.convertDate = function (expDate) {
        return expDate.getDate() + '/' + (expDate.getMonth() + 1) + '/' + expDate.getFullYear();
    };

    this.convertStatus = function (_status) {
        if (_status == 1)
            return MESSAGE.status_active;
        if (_status == 2)
            return MESSAGE.status_lock;
    };

    this.convertEndDate = function (_ed) {
        if (_ed == null)
            return MESSAGE.notDefault;
        else
            return COMMON.jSonDateToString(_ed, 1);
    };

}